package cn.kgc.kmall.product.service.impl;

import cn.kgc.kmall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.common.utils.PageUtils;
import cn.kgc.common.utils.Query;

import cn.kgc.kmall.product.dao.CategoryDao;
import cn.kgc.kmall.product.entity.CategoryEntity;
import cn.kgc.kmall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryDao categoryDao;
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    //写法一、查出所有分类以及子分类
    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查询所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //2、封装成父子的树形结构
        //2-1、找到所有的一级分类
        List<CategoryEntity> level1Menus = categoryEntities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                //获取下一级分类
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildrens(categoryEntity, categoryEntities));
                    return categoryEntity;
                })
                //按照sort字段排序
                .sorted((menu1, menu2) -> (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()))
                //把结果收集成集合
                .collect(Collectors.toList());
        return level1Menus;
    }

    //写法一、
    //获取分类的下级分类（递归查找所有菜单的子菜单）根据节点封装子节点 entity是父分类，从all里找出pid==entity.cid的元素
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> collect = all.stream()
                //获取下级分类
                .filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId())
                //递归调用
                .map(categoryEntity -> {
                    //1、找到子菜单
                    categoryEntity.setChildren(getChildrens(categoryEntity, all));
                    return categoryEntity;
                })
                //根据sort排序
                .sorted((menu1, menu2) -> (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()))
                //收集结果到集合
                .collect(Collectors.toList());
        return collect;
    }

    /**写法二、
    @Override
    public List<CategoryEntity> listWithTree(){
        //获取所有数据分类
        List<CategoryEntity> all= this.list();
        List<CategoryEntity> level1=new ArrayList<>()

    for(CategoryEntity categoryEntity : all){
        if(categoryEntity.getParentCid==0){
            level1.add(CategoryEntity);
            }
        }
    //为一级分类添加子分类
    for(CategoryEntity categoryEntity : level1){
            //获取子节点
            List<CategoryEntity> level2=getChildrens(categoryEntity,all);
            categoryEntity.setChildren(level2);
        }

    //排序
    level1=level1.stream()
        .sorted(o1,o2)->o1.getSort()==null?0:o1.getSort()-(o2.getSort()==null?0:o2.getSort()))
        .collect(Collectors.toList());
            return level1;
    }

     //根据节点封装子节点
     public List<CategoryEntity> getChildren(CategoryEntity entity,List<CategoryEntity> all){
    //子节点集合
    List<CategoryEntity> list=new ArrayList<>();
        if(CategoryEntity.getParentCid()==entity.getCatId()){
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            list.add(categoryEntity);
        }
    }

     //排序
     list=list.stream()
        .sorted((o1,o2)->o1.getSort()==null?0:o1.getSort()-(o2.getSort()==null?0:o2.getSort()))
        .collect(Collectors.toList());
     return list;
    */

    @Override
    public void removeMenuByIds(List<Long> longs) {

        //TODO 检查当前删除的菜单是否被使用(检查当前菜单是否被别的地方引用)

        baseMapper.deleteBatchIds(longs);
    }

    //后端收集一、二、三级分类的id
    //找到catelogId的完整路径
    @Override
    public List<Long> findCatelogPath(Long catelogId) {
        List<Long> paths=new ArrayList<>();
        findParentPath(catelogId,paths);
        Collections.reverse(paths);
        return paths;
    }


    //更新所有关联的数据
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);

        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){

        //添加自己的catelogId
        paths.add(catelogId);
        //根据id查询分类
        CategoryEntity categoryEntity = this.getById(catelogId);
        //添加父级catelogId
        if (categoryEntity.getParentCid()!=0){
            findParentPath(categoryEntity.getParentCid(),paths);
        }
        return paths;
    }

}